<?php

use console\db\Migration;
use yii\db\Query;
use yii\db\Expression;
use yii\helpers\ArrayHelper;

/**
 * 圈子回复评论内容分表
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class m300020_000014_t_sns_comment_sequence extends Migration {

    /**
     * @inheritdoc
     */
    public $sequenceTableName = 'sns_dynamic_comment';

    /**
     * @inheritdoc
     */
    public function safeUp() {
        $sequencesize = ArrayHelper::getValue(Yii::$app->params, 'sequence.table.' . $this->sequenceTableName);
        if (!$sequencesize) {
            return;
        }
        $masterTable = '{{%' . $this->sequenceTableName . '}}';

        $autoid = (new Query())->from($masterTable)->select(new Expression('max(id)'))->scalar();
        $this->update('{{sequence}}', [
            'generator' => $this->sequenceTableName,
            'id' => $autoid
        ]);

        $query = (new Query())->from($masterTable)->groupBy('dynamic_id');
        $this->handleProgress($query, [$this, 'evenDule'], $sequencesize);
    }

    /**
     * @inheritdoc
     */
    public function safeDown() {
        $this->truncateTable($this->tableName);
    }

    /**
     * 处理结果
     * @param Migration $migration
     * @param array $rows
     */
    public static function evenDule($migration, $rows, $parts) {
        $tableName = $migration->sequenceTableName;
        $masterTable = '{{%' . $tableName . '}}';
        $dynamicids = [];
        foreach ($rows as $row) {
            $dynamicid = $row['dynamic_id'];
            $part = $dynamicid % $parts;
            
            $tempTable = '{{%' . $tableName . '_' . $part . '}}';
            $query = (new Query())->from($masterTable)->select([
                'id',
                'user_id',
                'dynamic_id',
                'comment_id',
                'reply_id',
                'post',
                'author',
                'listener',
                'likes',
                'status',
                'created_at',
                'updated_at',
                'deleted_at',
            ])->andWhere([
                'dynamic_id' => $row['dynamic_id']
            ])->orderBy(['id' => SORT_ASC, 'created_at' => SORT_ASC]);
            $migration->db->createCommand()->insert($tempTable, $query)->execute();
            $dynamicids[] = $dynamicid;
        }
        if (empty($dynamicids)) {
            return;
        }
        $migration->db->createCommand()->delete($masterTable, [
            'dynamic_id' => $dynamicids
        ])->execute();
    }

}
